import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { ConfirmationService, MenuItem, MessageService } from 'primeng/api';
import { Location as Location1 } from '@angular/common';
import { MeterService } from 'src/app/service/meter.service';
import { DeviceService } from 'src/app/service/device.service';
import { transform } from 'src/app/service/utils/transform';
import { select, Store } from '@ngrx/store';
import { getMeterType } from 'src/app/store/utils/utils.reducer';
import { UtilsService } from 'src/app/service/utils.service';
import { WellService } from 'src/app/service/well.service';
import { HomeService } from 'src/app/service/home.service';
import { VolumeService } from 'src/app/service/volume.service';
import { AppState } from 'src/app/store/app.model';

@Component({
    selector: 'app-hydrant-info',
    templateUrl: './hydrant-info.component.html',
    styleUrls: ['./hydrant-info.component.scss'],
    providers: [ConfirmationService, MessageService],
})
export class HydrantInfoComponent implements OnInit {
    predictYear;
    meterData = [];
    meterstatus = [
        { label: '停用', value: 2 },
        { label: '正常', value: 1 },
        { label: '不正常', value: 0 },
    ];
    showMeter: any = false;
    addForm = {
        meterCode: '',
        meterName: '',
        status: '',
        meterNo: '',
        createTime: '',
        meterId: '',
    };
    blankAddForm = {
        meterCode: '',
        meterName: '',
        status: '',
        meterNo: '',
        createTime: '',
        meterId: '',
    };
    chartData: any;
    editTag: boolean = false;
    display: boolean = false;
    rangeTime = [new Date(Date.now() - 86400000 * 720), new Date()];
    rangeData: any;
    form = {
        wellName: '',
        wellCode: '',
        zone: { zoneId: '', zoneType: '' },
        longitude: '',
        latitude: '',
        irrigationArea: '',
        status: '',
        wellCaliber: '',
        wellDepth: '',
        createTime: '',
        comNumber: '',
        remark: '',
        wellType: '',
        wellUsage: '',
        wellId: '',
    };
    blankform = {
        wellName: '',
        wellCode: '',
        zone: { zoneId: '', zoneType: '' },
        longitude: '',
        latitude: '',
        irrigationArea: '',
        status: '',
        wellCaliber: '',
        wellDepth: '',
        createTime: '',
        comNumber: '',
        remark: '',
        wellType: '',
        wellUsage: '',
        wellId: '',
    };
    memory: any;
    status: any;
    chartOptions: any;
    id: any;
    param: any;
    visibleSidebar: boolean = false;
    visibleSidebar1: boolean = false;
    type: any;
    usage: any;
    address: any;
    currentTime: any;
    allData = undefined;
    currentYear = new Date();
    searchTimeType = '日';
    searchTime = new Date();
    meterType: any;
    totalData: any;
    timeTypes = [
        {
            value: '日',
            lable: '日',
        },
        {
            value: '月',
            lable: '月',
        },
        {
            value: '年',
            lable: '年',
        },
    ];
    genTwoLengthNumberString = (n) => (n >= 10 ? n : '0' + n);
    predictMonth: any;
    allDateTimeTrans(d) {
        if (!d) {
            return '';
        }
        let yy = d.getFullYear();
        let MM = this.genTwoLengthNumberString(d.getMonth() + 1);
        let dd = this.genTwoLengthNumberString(d.getDate());
        let hh = this.genTwoLengthNumberString(d.getHours());
        let mm = this.genTwoLengthNumberString(d.getMinutes());
        let ss = this.genTwoLengthNumberString(d.getSeconds());
        return yy + '-' + MM + '-' + dd + ' ' + hh + ':' + mm + ':' + ss;
    }
    dateTimeTrans(d) {
        if (!d) {
            return '';
        }
        let yy = d.getFullYear();
        let MM = this.genTwoLengthNumberString(d.getMonth() + 1);
        let dd = this.genTwoLengthNumberString(d.getDate());
        if (this.searchTimeType === '日') {
            return yy + '-' + MM + '-' + dd;
        }
        if (this.searchTimeType === '月') {
            return yy + '-' + MM;
        }
        if (this.searchTimeType === '年') {
            return yy;
        }
    }
    dateTimeTransHan(d) {
        if (!d) {
            return '';
        }
        let yy = d.getFullYear();
        let MM = this.genTwoLengthNumberString(d.getMonth() + 1);
        let dd = this.genTwoLengthNumberString(d.getDate());
        if (this.searchTimeType === '日') {
            return yy + '年' + MM + '月' + dd + '日';
        }
        if (this.searchTimeType === '月') {
            return yy + '年' + MM + '月';
        }
        if (this.searchTimeType === '年') {
            return yy + '年';
        }
        return null;
    }
    timeTypeTrans(str) {
        if (str === '日') {
            return 'day';
        } else if (str === '月') {
            return 'month';
        } else if (str === '年') {
            return 'year';
        }
        return 'unrecgonized';
    }
    async searchTotal() {
        // const res = await fetchStatisticsList(searchTimeType.value, dateTimeTrans(searchTime.value), searchTown.value)
        let currentTimeType = this.searchTimeType;
        let currentTime = this.dateTimeTransHan(this.searchTime);
        const res = await this.volumeService.fetchSpecificWellVolumeByTime({
            type: this.timeTypeTrans(this.searchTimeType),
            time: this.dateTimeTrans(this.searchTime),
            id: this.id,
        });
        //allData.value = res.data
        this.totalData = res.data;
    }
    async save() {
        const res = await this.wellService.updateWellInfoByConfig({
            ...this.form,
            wellId: this.id,
            zoneId: this.form.zone?.zoneId,
            zoneType: this.form.zone?.zoneType,
        });
        if (res.code === '200') {
            alert('修改成功');
            this.load();
        }
    }
    async load() {
        // console.log(id)
        // id = 70310
        if (this.id === undefined) {
            console.log('id is undefined');
        } else {
            const res = await this.wellService.fetchWellInfoById({
                wellId: this.id,
            });
            //const res2 = await fetchDevicesById(id)
            //console.log(res2.data)
            console.log(res.data);
            if (res.code === '200') {
                // testData = res.data
                //assignForm(res.data)
                this.memory = res.data;
                this.form = res.data;
            }
            // console.log(testData[0]['name'])
        }
    }
    constructor(
        private router: Router,
        private location: Location1,
        private route: ActivatedRoute,
        private wellService: WellService,
        private transform: transform,
        private utilsService: UtilsService,
        private homeService: HomeService,
        private volumeService: VolumeService,
        private store: Store<AppState>,
        private deviceService: DeviceService,
        private meterService: MeterService,
        private confirmationService: ConfirmationService,
        private messageService: MessageService
    ) {
        this.status = transform.statuss;
        this.type = transform.types;
        this.usage = transform.usages;
        route.queryParams.subscribe((queryParams) => {
            this.id = queryParams.id;
        });
        this.store.pipe(select(getMeterType)).subscribe((data) => {
            let types = data || [];
            this.meterType = types.map((item) => ({
                label: item.meterNo,
                value: item.id,
            }));
        });
    }
    searchLine = async () => {
        const current = this.currentYear.getFullYear();
        const id = this.id;
        const res1 = await this.homeService.fetchMounthCostByYearAndWell({
            year: current,
            id,
        });
        if (res1.code != 200) {
            return;
        }
        const res2 = await this.homeService.fetchMounthCostByYearAndWell({
            year: current - 1,
            id,
        });
        if (res2.code != 200) {
            return;
        }
        const res3 = await this.homeService.fetchMounthCostByYearAndWell({
            year: current - 2,
            id,
        });
        if (res3.code != 200) {
            return;
        }
        let r1 = [];
        let r2 = [];
        let r3 = [];
        if (res1.code === '200' && res2.code === '200' && res3.code === '200') {
            let g = [];
            // r1 = res1.data.map(item => item.value)
            // for (let i = 0; i < 12; i++) {
            //   const tmp = res1.data.find(item => item.time === current + '-' + (i + 1 >= 10 ? i + 1 : '0' + (i + 1)))
            //   r1.push(tmp ? tmp.monthData : undefined)
            // }
            // for (let i = 0; i < 12; i++) {
            //   const tmp = res2.data.find(item => item.time === current - 1 + '-' + (i + 1 >= 10 ? i + 1 : '0' + (i + 1)))
            //   r2.push(tmp ? tmp.monthData : undefined)
            // }
            // for (let i = 0; i < 12; i++) {
            //   const tmp = res3.data.find(item => item.time === current - 2 + '-' + (i + 1 >= 10 ? i + 1 : '0' + (i + 1)))
            //   r3.push(tmp ? tmp.monthData : undefined)
            // }
            r1 = res1.data.map((item) => item.volume);
            r2 = res2.data.map((item) => item.volume);
            r3 = res3.data.map((item) => item.volume);
            console.log(r1, r2, r3);
            this.chartData = {
                labels: [
                    '1月',
                    '2月',
                    '3月',
                    '4月',
                    '5月',
                    '6月',
                    '7月',
                    '8月',
                    '9月',
                    '10月',
                    '11月',
                    '12月',
                ],
                datasets: [
                    {
                        type: 'line',
                        label: this.currentYear.getFullYear() + '年',
                        data: r1,
                        fill: false,
                        backgroundColor: '#00bb7e',
                        borderColor: '#00bb7e',
                    },
                    {
                        type: 'line',
                        label: this.currentYear.getFullYear() - 1 + '年',
                        data: r2,
                        fill: false,
                        backgroundColor: '#42A5F5',
                        borderColor: '#42A5F5',
                    },
                    {
                        type: 'line',
                        label: this.currentYear.getFullYear() - 2 + '年',
                        data: r3,
                        fill: false,
                        backgroundColor: '#FFA726',
                        borderColor: '#FFA726',
                    },
                ],
            };
        }
    };
    ngOnInit() {
        this.load();
        //console.log(this.id);
        this.address = this.utilsService.addressOption();
        this.searchLine();
        this.searchTotal();
        this.searchRange();
        this.searchMeter();
        this.getYearPredict();
        this.getMonthPredict();
    }
    goBack() {
        this.location.back();
    }
    openDialog(a, item?) {
        console.log(a);
        this.display = true;
        this.editTag = a;
        if (a) {
            this.addForm = {
                ...item,
                createTime: new Date(item.createTime),
            };
            console.log(this.addForm);
        } else {
            this.addForm = {
                ...this.blankAddForm,
            };
        }
    }
    reset() {
        console.log('reset');
        this.form = {
            ...this.memory,
        };
    }
    resetTotal() {
        this.searchTimeType = '日';
        this.searchTime = new Date();
        this.searchTotal();
    }
    async searchRange() {
        //console.log(this.rangeTime)
        const res = await this.volumeService.fetchWellDataByConfig({
            id: this.id,
            start: this.dateTimeTrans(this.rangeTime[0]),
            end: this.dateTimeTrans(this.rangeTime[1]),
        });
        this.rangeData = res.data;
    }
    resetRange() {
        this.rangeTime = [new Date(Date.now() - 86400000 * 720), new Date()];
        this.searchRange();
    }
    async submitMeter() {
        if (this.editTag == true) {
            this.updateMeter();
        } else {
            const r = await this.meterService.insertMeterInfo({
                wellId: this.id,
                meterName: this.addForm.meterName,
                meterCode: this.addForm.meterCode,
                createTime: this.allDateTimeTrans(this.addForm.createTime),
                status: this.addForm.status,
                meterNo: this.addForm.meterNo,
            });
            console.log(r);
            if (r.code === '200') {
                this.messageService.add({
                    severity: 'info',
                    summary: '确认',
                    detail: '你已经新增相关的机电设备',
                });
                this.searchMeter();
                //location.reload()
            }
            this.display = false;
        }
    }
    async searchMeter() {
        //console.log(usingId.value);
        if (!this.id) {
            return;
        }
        const res = await this.deviceService.fetchDevicesById({
            well_id: this.id,
        });
        console.log(res);
        this.meterData = res.data;
    }
    async deleteMeter(item) {
        this.confirmationService.confirm({
            message: '请问你确认删除吗 ?',
            header: '警告',
            icon: 'pi pi-exclamation-triangle',
            accept: async () => {
                console.log(item);
                const r = await this.meterService.deleteMeterInfo({
                    meter_id: item.meterId,
                });
                if (r.code == 200) {
                    this.messageService.add({
                        severity: 'info',
                        summary: '确认',
                        detail: '你已经删除',
                    });
                    this.searchMeter();
                }
            },
        });
    }
    async updateMeter() {
        const r = await this.meterService.updateMeterInfo({
            meterId: this.addForm.meterId,
            meterCode: this.addForm.meterCode,
            meterNo: this.addForm.meterNo, // 类型
            meterName: this.addForm.meterName,
            status: this.addForm.status,
            createTime: this.allDateTimeTrans(this.addForm.createTime),
        });
        if (r.code === '200') {
            this.messageService.add({
                severity: 'info',
                summary: '确认',
                detail: '你已经更新',
            });
            this.searchMeter();
            this.searchMeter();
            this.display = false;
        }
    }
    async getYearPredict() {
        const res = await this.wellService.fetchWellYearPredictById({
            wellId: this.id,
        });
        console.log(res.data);
        this.predictYear = (res.data / 1000).toFixed(2);
    }
    async getMonthPredict() {
        const res = await this.wellService.fetchWellMonthPredictById({
            wellId:this.id,
            year:new Date().getFullYear()
        });
        console.log(res.data);
        if(res.data=="Null")this.predictMonth = 0
        else this.predictMonth = res.data/1000;
        this.predictMonth = this.predictMonth.toFixed(2)

    }
}
